﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Workflow2211A.Domain.Entities;

namespace Workflow2211A.Domain
{
    /// <summary>
    /// 仓储基类
    /// </summary>
    /// <typeparam name="T">实体</typeparam>
    public class BaseRepository<T> : IBaseRepository<T> where T : BaseEntity
    {
        /// <summary>
        /// 数据库上下文
        /// </summary>
        private readonly Workflow2211Context db;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="db">数据上下文</param>
        public BaseRepository(Workflow2211Context db)
        {
            this.db = db;
        }
        /// <summary>
        /// 获取全部
        /// </summary>
        /// <returns>返回集合</returns>
        public IQueryable<T> GetAll()
        {
            return db.Set<T>().AsQueryable();
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响行数</returns>
        public int Add(T entity)
        {
            db.Set<T>().Add(entity);
            return db.SaveChanges();
        }
        /// <summary>
        /// 异步泛型添加
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> AddAsync(T entity)
        { 
            await db.Set<T>().AddAsync(entity);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响行数</returns>
        public int Update(T entity)
        {
            db.Set<T>().Update(entity);
            return  db.SaveChanges();
        }
    }
}
